package com.test.burnincash.aaahpoppomelo.util.http_hpoppomelo;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.test.burnincash.BuildConfig;
import com.test.burnincash.bean_burnin.config_info_burnin.UrlInfo_burnin;
import com.test.burnincash.constant_burnin.Constant_burnin;
import com.test.burnincash.constant_burnin.Url_burnin;
import com.test.burnincash.util_burnin.StringUtil_burnin;
import com.test.burnincash.util_burnin.ThreadUtil_burnin;
import com.test.burnincash.util_burnin.analytics_burnin.util_burnin.AnalyticsUtil_burnin;
import com.test.burnincash.util_burnin.helper_burnin.UserInfoHelper_burnin;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpManager_hpoppomelo {

    private HttpManager_hpoppomelo() {
        if (BuildConfig.DEBUG) {
            mHttpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }
        mClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(mHttpLoggingInterceptor)
                .addInterceptor(new ReqInterceptor_hpoppomelo())
                .callTimeout(5000, TimeUnit.MILLISECONDS)
                .build();
    }

    private static class Inner {
        private static final HttpManager_hpoppomelo instance = new HttpManager_hpoppomelo();
    }

    public static HttpManager_hpoppomelo getInstance() {
        return Inner.instance;
    }

    private static OkHttpClient mClient;

    private static final HttpLoggingInterceptor mHttpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLogger_hpoppomelo());

    //请求响应回调
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            HttpPresenter_hpoppomelo.getInstance().showToastOnUiThread("Request Fail");
            ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_hpoppomelo.getInstance().progressBarDialogDismiss());
            Log.e("Http Response", "Request Fail");
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            String body = Objects.requireNonNull(response.body()).string();
            ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_hpoppomelo.getInstance().progressBarDialogDismiss());
            try {
                String word = StringUtil_burnin.getUrlSuffix(response.request().url().toString());
                handleResponse(word, new JSONObject(body));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    //处理响应
    private void handleResponse(String lastWord, JSONObject responseJson) {
        ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_hpoppomelo.getInstance().notifyActivityHandleResponse(lastWord, responseJson));
    }

    //获取初始化JSON对象
    @NonNull
    private JSONObject getRequestJson() {
        return getRequestJson(new JSONObject());
    }

    private JSONObject getRequestJson(JSONObject jsonObject) {
        try {
            jsonObject.put("isLimitAdTrackingEnabled", AnalyticsUtil_burnin.INSTANCE.getAdEnabled() + "");
            jsonObject.put("aduid", AnalyticsUtil_burnin.INSTANCE.getAdId());
            jsonObject.put("aduidPath", AnalyticsUtil_burnin.INSTANCE.getAndroidId());
            jsonObject.put("version", Constant_burnin.APP_VERSION.trim());
            jsonObject.put("token", UserInfoHelper_burnin.getInstance().getToken().trim());
            jsonObject.put("androidId", AnalyticsUtil_burnin.INSTANCE.getAndroidId());
            jsonObject.put("userId", UserInfoHelper_burnin.getInstance().getUserId().trim());
            jsonObject.put("advertId", AnalyticsUtil_burnin.INSTANCE.getAdId());
            jsonObject.put("product", Constant_burnin.PRODUCT.trim());
            jsonObject.put("clientType", Constant_burnin.CLIENT.trim());
            jsonObject.put("apiVersion", "v3");
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //发送请求
    private void request(String lastWord, String jsonString) {
        requestWithoutCountryPrefix(Url_burnin.PATH_GLOBAL + lastWord,jsonString);
    }

    //发送请求（不带国家前缀）
    private void requestWithoutCountryPrefix(String lastWord, String jsonString) {

        ThreadUtil_burnin.getInstance().runOnUiThread(() -> HttpPresenter_hpoppomelo.getInstance().progressBarDialogShow());

        ThreadUtil_burnin.getInstance().runOnChildThread(() -> {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            Request request = new Request.Builder()
                    .url(Url_burnin.Url_Base + lastWord)
                    .post(RequestBody.Companion.create(jsonString, mediaType))
                    .build();
            Call call = mClient.newCall(request);
            call.enqueue(callback);
        });
    }

    /**
     * 保存页面显示/隐藏打点
     */
    public void saveUserBuriedPoint(String pageEvent) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = getRequestJson();
                jsonObject.put("type", Constant_burnin.PRODUCT +"_"+pageEvent);

                final String gurl = Url_burnin.Url_Base + Url_burnin.PATH_GLOBAL + Url_burnin.PATH_USER_BURIED_POINT;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient.newCall(request);
                call.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 保存
     */
    public void saveData(String data){
        JSONObject jsonObject = getRequestJson();
        try {
            jsonObject.put("type",data);
            jsonObject.put("remark","remark");
            jsonObject.put("date","2022-02-02");
            jsonObject.put("amount","amount");
            jsonObject.put("transfer","transfer");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        request(UrlInfo_burnin.getInstance().getXc2(),jsonObject.toString());
    }

    /**
     * 读取
     */
    public void getData(){
        request(UrlInfo_burnin.getInstance().getNvb(),getRequestJson().toString());
    }

}
